{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "name": "22 - Transform tabular data with composable workflows",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4Pjmz-RORV8E"
      },
      "source": [
        "# Transform tabular data with composable workflows\n",
        "\n",
        "_This notebook is part of a tutorial series on [txtai](https://github.com/neuml/txtai), an AI-powered semantic search platform._\n",
        "\n",
        "txtai executes machine-learning workflows to transform data and build AI-powered semantic search applications. txtai has support for processing both unstructured and structured data. Structured or tabular data is grouped into rows and columns. This can be a spreadsheet, an API call that returns JSON or XML or even list of key-value pairs.\n",
        "\n",
        "This notebook will walk through examples on how to use workflows with the tabular pipeline to transform and index structured data.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dk31rbYjSTYm"
      },
      "source": [
        "# Install dependencies\n",
        "\n",
        "Install `txtai` and all dependencies. We will install the api, pipeline and workflow optional extras packages. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XMQuuun2R06J"
      },
      "source": [
        "%%capture\n",
        "!pip install git+https://github.com/neuml/txtai#egg=txtai[api,pipeline,workflow] sacremoses"
      ],
      "execution_count": 66,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NSYrP0hjtR_E"
      },
      "source": [
        "# CSV Workflow\n",
        "\n",
        "The first example will transform and index a CSV file. The [COVID-19 Open Research Dataset](https://allenai.org/data/cord-19) (CORD-19) is a repository of medical articles covering COVID-19. This workflow reads the input CSV and builds a semantic search index.\n",
        "\n",
        "The first step is downloading the dataset locally."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BoPJIKWoTibk"
      },
      "source": [
        "%%capture\n",
        "# Get CORD-19 metadata file\n",
        "!wget https://ai2-semanticscholar-cord-19.s3-us-west-2.amazonaws.com/2021-11-01/metadata.csv\n",
        "!head -1 metadata.csv > input.csv\n",
        "!tail -10000 metadata.csv >> input.csv"
      ],
      "execution_count": 67,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q1ivX4eBuU8T"
      },
      "source": [
        "The next section creates a simple workflow consisting of a tabular pipeline. The tabular pipeline builds a list of (id, text, tag) tuples that can be easily loaded into an Embeddings index. For this example, we'll use the `url` column as the id and the `title` column as the text column. The textcolumns parameter takes a list of columns to support indexing text content from multiple columns. \n",
        "\n",
        "The file input.csv is processed and the first 5 rows are shown."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-pi2QU3TSlM_",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a30ffeb2-1d85-467b-a0a3-134c8cbac19f"
      },
      "source": [
        "from txtai.pipeline import Tabular\n",
        "from txtai.workflow import Task, Workflow\n",
        "\n",
        "# Create tabular instance mapping input.csv fields\n",
        "tabular = Tabular(\"url\", [\"title\"])\n",
        "\n",
        "# Create workflow\n",
        "workflow = Workflow([Task(tabular)])\n",
        "\n",
        "# Print 5 rows of input.csv via workflow\n",
        "list(workflow([\"input.csv\"]))[:5]"
      ],
      "execution_count": 68,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[('https://doi.org/10.1016/j.cmpb.2021.106469; https://www.ncbi.nlm.nih.gov/pubmed/34715516/',\n",
              "  'Computer simulation of the dynamics of a spatial susceptible-infected-recovered epidemic model with time delays in transmission and treatment.',\n",
              "  None),\n",
              " ('https://www.ncbi.nlm.nih.gov/pubmed/34232002/; https://doi.org/10.36849/jdd.5544',\n",
              "  'Understanding the Potential Role of Abrocitinib in the Time of SARS-CoV-2',\n",
              "  None),\n",
              " ('https://doi.org/10.1186/1471-2458-8-42; https://www.ncbi.nlm.nih.gov/pubmed/18234083/',\n",
              "  \"Can the concept of Health Promoting Schools help to improve students' health knowledge and practices to combat the challenge of communicable diseases: Case study in Hong Kong?\",\n",
              "  None),\n",
              " ('https://www.ncbi.nlm.nih.gov/pubmed/32983582/; https://www.sciencedirect.com/science/article/pii/S2095809920302514?v=s5; https://api.elsevier.com/content/article/pii/S2095809920302514; https://doi.org/10.1016/j.eng.2020.07.018',\n",
              "  'Buying time for an effective epidemic response: The impact of a public holiday for outbreak control on COVID-19 epidemic spread',\n",
              "  None),\n",
              " ('https://doi.org/10.1093/pcmedi/pbab016',\n",
              "  'The SARS-CoV-2 spike L452R-E484Q variant in the Indian B.1.617 strain showed significant reduction in the neutralization activity of immune sera',\n",
              "  None)]"
            ]
          },
          "metadata": {},
          "execution_count": 68
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "UYYKnwNhu0hv"
      },
      "source": [
        "Next, we take the workflow output, build an Embeddings index and run a search query."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "G7M34puLWeZm",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0e9e771b-d53d-4c4e-8ac8-257c33992f66"
      },
      "source": [
        "from txtai.embeddings import Embeddings\n",
        "\n",
        "# Embeddings with sentence-transformers backend\n",
        "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",
        "\n",
        "# Index subset of CORD-19 data\n",
        "data = list(workflow([\"input.csv\"]))\n",
        "embeddings.index(data)\n",
        "\n",
        "for uid, _ in embeddings.search(\"insulin\"):\n",
        "  title = [text for url, text, _ in data if url == uid][0]\n",
        "  print(title, uid)"
      ],
      "execution_count": 69,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Importance of diabetes management during the COVID-19 pandemic. https://doi.org/10.1080/00325481.2021.1978704; https://www.ncbi.nlm.nih.gov/pubmed/34602003/\n",
            "Position Statement on How to Manage Patients with Diabetes and COVID-19 https://www.ncbi.nlm.nih.gov/pubmed/33442169/; https://doi.org/10.15605/jafes.035.01.03\n",
            "Successful blood glucose management of a severe COVID-19 patient with diabetes: A case report https://www.ncbi.nlm.nih.gov/pubmed/32590779/; https://doi.org/10.1097/md.0000000000020844\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vPQv7GJSu9Uq"
      },
      "source": [
        "The example searched for the term `insulin`. The top results mention diabetes and blood glucose which are a closely associated terms for diabetes."
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Workflow with stored content\n",
        "\n",
        "Next we'll re-run the same example adding in full content storage. Full content storage enables SQL queries."
      ],
      "metadata": {
        "id": "BQeLRC1md6GR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import json\n",
        "\n",
        "# Create tabular instance mapping input.csv fields\n",
        "tabular = Tabular(\"url\", [\"title\"], True)\n",
        "\n",
        "# Create workflow\n",
        "workflow = Workflow([Task(tabular)])\n",
        "\n",
        "# Embeddings with sentence-transformers backend\n",
        "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\", \"content\": True})\n",
        "\n",
        "# Index subset of CORD-19 data\n",
        "data = list(workflow([\"input.csv\"]))\n",
        "embeddings.index(data)\n",
        "\n",
        "for result in embeddings.search(\"select title, abstract, authors, doi from txtai where similar('insulin')\"):\n",
        "  print(json.dumps(result, default=str, indent=2))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Ln61lB7QeDEq",
        "outputId": "ae364e17-36a5-480e-c614-c7e58d8b8462"
      },
      "execution_count": 70,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{\n",
            "  \"title\": \"Importance of diabetes management during the COVID-19 pandemic.\",\n",
            "  \"abstract\": \"Uncontrolled diabetes and/or hyperglycemia is associated with severe COVID-19 disease and increased mortality. It is now known that poor glucose control before hospital admission can be associated with a high risk of in-hospital death. By achieving and maintaining glycemic control, primary care physicians (PCPs) play a critical role in limiting this potentially devastating outcome. Further, despite the hope that mass vaccination will help control the pandemic, genetic variants of the virus are causing surges in some countries. As such, PCPs will treat an increasing number of patients with diabetes who have symptoms of post-COVID-19 infection, or even have new-onset type 2 diabetes as a result of COVID-19 infection. However, much of the literature published focuses on the effects of COVID-19 in hospitalized patients, with few publications providing information and advice to those caring for people with diabetes in the primary care setting. This manuscript reviews the current knowledge of the risk and outcomes of individuals with diabetes who are infected with COVID-19 and provides information for PCPs on the importance of glucose control, appropriate treatment, and use of telemedicine and online prescription delivery systems to limit the potentially devastating effects of COVID-19 in people with hyperglycemia.\",\n",
            "  \"authors\": \"Pettus, Jeremy; Skolnik, Neil\",\n",
            "  \"doi\": \"10.1080/00325481.2021.1978704\"\n",
            "}\n",
            "{\n",
            "  \"title\": \"Position Statement on How to Manage Patients with Diabetes and COVID-19\",\n",
            "  \"abstract\": null,\n",
            "  \"authors\": null,\n",
            "  \"doi\": \"10.15605/jafes.035.01.03\"\n",
            "}\n",
            "{\n",
            "  \"title\": \"Successful blood glucose management of a severe COVID-19 patient with diabetes: A case report\",\n",
            "  \"abstract\": \"RATIONALE: Coronavirus disease 2019 (COVID-19) has emerged as a rapidly spreading communicable disease affecting individuals worldwide. Patients with diabetes are more vulnerable to the disease, and the mortality is higher than in those without diabetes. We reported a severe COVID-19 patient with diabetes and shared our experience with blood glucose management. PATIENT CONCERNS: A 64-year-old female diabetes patient was admitted to the intensive care unit due to productive coughing for 8 days without any obvious cause. The results of blood gas analysis indicated that the partial pressure of oxygen was 84 mm Hg with oxygen 8 L/min, and the oxygenation index was less than 200 mm Hg. In addition, postprandial blood glucose levels were abnormal (29.9 mmol/L). DIAGNOSES: The patient was diagnosed with COVID-19 (severe type) and type 2 diabetes. INTERVENTIONS: Comprehensive interventions including establishing a multidisciplinary team, closely monitoring her blood glucose level, an individualized diabetes diet, early activities, psychological care, etc, were performed to control blood glucose while actively treating COVID-19 infection. OUTCOMES: After the comprehensive measures, the patient's blood glucose level gradually became stable, and the patient was discharged after 20 days of hospitalization. LESSONS: This case indicated that the comprehensive measures performed by a multidisciplinary team achieved good treatment effects on a COVID-19 patient with diabetes. Targeted treatment and nursing methods should be performed based on patients\\u2019 actual situations in clinical practice.\",\n",
            "  \"authors\": \"Hu, Rujun; Gao, Huiming; Huang, Di; Jiang, Deyu; Chen, Fang; Fu, Bao; Yuan, Xiaoli; Li, Jin; Jiang, Zhixia\",\n",
            "  \"doi\": \"10.1097/md.0000000000020844\"\n",
            "}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Note how the same results are returned with additional content fields."
      ],
      "metadata": {
        "id": "yTvn0O1v_eHT"
      }
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gzFmQDXfvniJ"
      },
      "source": [
        "# JSON Service Workflow\n",
        "\n",
        "The next example builds a workflow that runs a query against a remote URL, retrieves the results, then transforms and indexes the tabular data. This example gets the top results from the [Hacker News front page](https://news.ycombinator.com/). \n",
        "\n",
        "Below shows how to build the ServiceTask and prints the first JSON result. Details on how to configure the ServiceTask can be found in [txtai's documentation](https://neuml.github.io/txtai/workflows/)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "bA8SihkeZqbJ",
        "outputId": "05962fa0-7e79-49a8-b6ac-3d535ace3fad"
      },
      "source": [
        "from txtai.workflow import ServiceTask\n",
        "\n",
        "service = ServiceTask(url=\"https://hn.algolia.com/api/v1/search\", method=\"get\", params={\"tags\": None}, batch=False, extract=\"hits\")\n",
        "workflow = Workflow([service])\n",
        "\n",
        "list(workflow([\"front_page\"]))[0][2]"
      ],
      "execution_count": 71,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'_highlightResult': {'author': {'matchLevel': 'none',\n",
              "   'matchedWords': [],\n",
              "   'value': 'cheesestain'},\n",
              "  'title': {'matchLevel': 'none',\n",
              "   'matchedWords': [],\n",
              "   'value': 'Ante: A low-level functional language'},\n",
              "  'url': {'matchLevel': 'none',\n",
              "   'matchedWords': [],\n",
              "   'value': 'https://antelang.org/'}},\n",
              " '_tags': ['story', 'author_cheesestain', 'story_31775216', 'front_page'],\n",
              " 'author': 'cheesestain',\n",
              " 'comment_text': None,\n",
              " 'created_at': '2022-06-17T07:39:40.000Z',\n",
              " 'created_at_i': 1655451580,\n",
              " 'num_comments': 109,\n",
              " 'objectID': '31775216',\n",
              " 'parent_id': None,\n",
              " 'points': 207,\n",
              " 'story_id': None,\n",
              " 'story_text': None,\n",
              " 'story_title': None,\n",
              " 'story_url': None,\n",
              " 'title': 'Ante: A low-level functional language',\n",
              " 'url': 'https://antelang.org/'}"
            ]
          },
          "metadata": {},
          "execution_count": 71
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Lv_ybw1VwK1N"
      },
      "source": [
        "Next we'll map the JSON data using the tabular pipeline. `url` will be used as the id column and `title` as the text to index."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YAbwhsaveKo1",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "15c1b28a-3c16-4d38-c586-6b8eae244dbb"
      },
      "source": [
        "from txtai.workflow import Task\n",
        "\n",
        "# Create tabular instance mapping input.csv fields\n",
        "tabular = Tabular(\"url\", [\"title\"])\n",
        "\n",
        "# Recreate service applying the tabular pipeline to each result\n",
        "service = ServiceTask(action=tabular, url=\"https://hn.algolia.com/api/v1/search\", method=\"get\", params={\"tags\": None}, batch=False, extract=\"hits\")\n",
        "workflow = Workflow([service])\n",
        "\n",
        "list(workflow([\"front_page\"]))[2]"
      ],
      "execution_count": 72,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "('https://antelang.org/', 'Ante: A low-level functional language', None)"
            ]
          },
          "metadata": {},
          "execution_count": 72
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SbjMuN5lw63c"
      },
      "source": [
        "As we did previously, let's build an Embeddings index and run a search query."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5lx9pa65e23E",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "99e05da7-b013-4d17-d82b-c7e13e79a563"
      },
      "source": [
        "# Embeddings with sentence-transformers backend\n",
        "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",
        "\n",
        "# Index Hacker News front page\n",
        "data = list(workflow([\"front_page\"]))\n",
        "embeddings.index(data)\n",
        "\n",
        "for uid, _ in embeddings.search(\"programming\"):\n",
        "  title = [text for url, text, _ in data if url == uid][0]\n",
        "  print(title, uid)"
      ],
      "execution_count": 73,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Bundling binary tools in Python wheels https://simonwillison.net/2022/May/23/bundling-binary-tools-in-python-wheels/\n",
            "Ante: A low-level functional language https://antelang.org/\n",
            "Adding a Rust compiler front end to GCC [video] https://www.youtube.com/watch?v=R8Pr21nlhig\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yq26KqfgxJ6Q"
      },
      "source": [
        "# XML Service workflow\n",
        "\n",
        "txtai's ServiceTask can consume both JSON and XML. This example runs a query against the [arXiv API](https://arxiv.org/), transforms the results and indexes them for search.\n",
        "\n",
        "Below shows how to build the ServiceTask and prints the first XML result."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "K6CbS2QwltGi",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2d9a0336-9680-4ca1-e2cd-68f6c5b4d1d3"
      },
      "source": [
        "service = ServiceTask(url=\"http://export.arxiv.org/api/query\", method=\"get\", params={\"search_query\": None, \"max_results\": 25}, batch=False, extract=[\"feed\", \"entry\"])\n",
        "workflow = Workflow([service])\n",
        "\n",
        "list(workflow([\"all:aliens\"]))[0][:1]"
      ],
      "execution_count": 74,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[{'arxiv:comment': {'#text': 'To appear in Astrophysical Journal',\n",
              "   '@xmlns:arxiv': 'http://arxiv.org/schemas/atom'},\n",
              "  'arxiv:doi': {'#text': '10.3847/1538-4357/ac2369',\n",
              "   '@xmlns:arxiv': 'http://arxiv.org/schemas/atom'},\n",
              "  'arxiv:primary_category': {'@scheme': 'http://arxiv.org/schemas/atom',\n",
              "   '@term': 'q-bio.OT',\n",
              "   '@xmlns:arxiv': 'http://arxiv.org/schemas/atom'},\n",
              "  'author': [{'name': 'Robin Hanson'},\n",
              "   {'name': 'Daniel Martin'},\n",
              "   {'name': 'Calvin McCarter'},\n",
              "   {'name': 'Jonathan Paulson'}],\n",
              "  'category': [{'@scheme': 'http://arxiv.org/schemas/atom',\n",
              "    '@term': 'q-bio.OT'},\n",
              "   {'@scheme': 'http://arxiv.org/schemas/atom', '@term': 'physics.pop-ph'}],\n",
              "  'id': 'http://arxiv.org/abs/2102.01522v3',\n",
              "  'link': [{'@href': 'http://dx.doi.org/10.3847/1538-4357/ac2369',\n",
              "    '@rel': 'related',\n",
              "    '@title': 'doi'},\n",
              "   {'@href': 'http://arxiv.org/abs/2102.01522v3',\n",
              "    '@rel': 'alternate',\n",
              "    '@type': 'text/html'},\n",
              "   {'@href': 'http://arxiv.org/pdf/2102.01522v3',\n",
              "    '@rel': 'related',\n",
              "    '@title': 'pdf',\n",
              "    '@type': 'application/pdf'}],\n",
              "  'published': '2021-02-01T18:27:12Z',\n",
              "  'summary': \"If life on Earth had to achieve n 'hard steps' to reach humanity's level,\\nthen the chance of this event rose as time to the n-th power. Integrating this\\nover habitable star formation and planet lifetime distributions predicts >99%\\nof advanced life appears after today, unless n<3 and max planet duration\\n<50Gyr. That is, we seem early. We offer this explanation: a deadline is set by\\n'loud' aliens who are born according to a hard steps power law, expand at a\\ncommon rate, change their volumes' appearances, and prevent advanced life like\\nus from appearing in their volumes. 'Quiet' aliens, in contrast, are much\\nharder to see. We fit this three-parameter model of loud aliens to data: 1)\\nbirth power from the number of hard steps seen in Earth history, 2) birth\\nconstant by assuming a inform distribution over our rank among loud alien birth\\ndates, and 3) expansion speed from our not seeing alien volumes in our sky. We\\nestimate that loud alien civilizations now control 40-50% of universe volume,\\neach will later control ~10^5 - 3x10^7 galaxies, and we could meet them in\\n~200Myr - 2Gyr. If loud aliens arise from quiet ones, a depressingly low\\ntransition chance (~10^-4) is required to expect that even one other quiet\\nalien civilization has ever been active in our galaxy. Which seems bad news for\\nSETI. But perhaps alien volume appearances are subtle, and their expansion\\nspeed lower, in which case we predict many long circular arcs to find in our\\nsky.\",\n",
              "  'title': 'If Loud Aliens Explain Human Earliness, Quiet Aliens Are Also Rare',\n",
              "  'updated': '2021-09-06T14:18:23Z'}]"
            ]
          },
          "metadata": {},
          "execution_count": 74
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aWFwkxjQyscc"
      },
      "source": [
        "Next we'll map the XML data using the tabular pipeline. `id` will be used as the id column and `title` as the text to index."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DyIetJ7OmJjP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7e730b22-256d-4b1b-9064-2479e26d50c9"
      },
      "source": [
        "from txtai.workflow import Task\n",
        "\n",
        "# Create tablular pipeline with new mapping\n",
        "tabular = Tabular(\"id\", [\"title\"])\n",
        "\n",
        "# Recreate service applying the tabular pipeline to each result\n",
        "service = ServiceTask(action=tabular, url=\"http://export.arxiv.org/api/query\", method=\"get\", params={\"search_query\": None, \"max_results\": 25}, batch=False, extract=[\"feed\", \"entry\"])\n",
        "workflow = Workflow([service])\n",
        "\n",
        "list(workflow([\"all:aliens\"]))[:1]"
      ],
      "execution_count": 75,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[('http://arxiv.org/abs/2102.01522v3',\n",
              "  'If Loud Aliens Explain Human Earliness, Quiet Aliens Are Also Rare',\n",
              "  None)]"
            ]
          },
          "metadata": {},
          "execution_count": 75
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7pFnW7mCyycy"
      },
      "source": [
        "As we did previously, let's build an Embeddings index and run a search query."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NX2oR5dhm_99",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "399c4316-bce6-443b-c383-aedd7ff9a1ec"
      },
      "source": [
        "# Embeddings with sentence-transformers backend\n",
        "embeddings = Embeddings({\"method\": \"transformers\", \"path\": \"sentence-transformers/paraphrase-mpnet-base-v2\"})\n",
        "\n",
        "# Index Hacker News front page\n",
        "data = list(workflow([\"all:aliens\"]))\n",
        "embeddings.index(data)\n",
        "\n",
        "for uid, _ in embeddings.search(\"alien radio signals\"):\n",
        "  title = [text for url, text, _ in data if url == uid][0]\n",
        "  print(title, uid)"
      ],
      "execution_count": 76,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Calculating the probability of detecting radio signals from alien\n",
            "  civilizations http://arxiv.org/abs/0707.0011v2\n",
            "Field Trial of Alien Wavelengths on GARR Optical Network http://arxiv.org/abs/1805.04278v1\n",
            "Aliens on Earth. Are reports of close encounters correct? http://arxiv.org/abs/1203.6805v2\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8xknLo2ey0vZ"
      },
      "source": [
        "# Build a workflow with no code!\n",
        "\n",
        "The next example shows how one of the same workflows above can be constructed via API configuration. This is a no-code way to build a txtai indexing workflow!"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1eF5IJlzpNbw",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4ff0bfdc-fb01-46a6-b61a-142a370dc273"
      },
      "source": [
        "%%writefile workflow.yml\n",
        "# Index settings\n",
        "writable: true\n",
        "embeddings:\n",
        "    path: sentence-transformers/nli-mpnet-base-v2\n",
        "\n",
        "# Tabular pipeline\n",
        "tabular:\n",
        "  idcolumn: id\n",
        "  textcolumns: \n",
        "    - title\n",
        "\n",
        "# Workflow definitions\n",
        "workflow:\n",
        "  index:\n",
        "    tasks:\n",
        "      - task: service\n",
        "        action: tabular\n",
        "        url: http://export.arxiv.org/api/query?max_results=25\n",
        "        method: get\n",
        "        params:\n",
        "          search_query: null\n",
        "        batch: false\n",
        "        extract: [feed, entry]\n",
        "      - action: upsert"
      ],
      "execution_count": 77,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Writing workflow.yml\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dxi5w3IezR7Q"
      },
      "source": [
        "This workflow once again runs an arXiv query and indexes article titles. The workflow configures the same actions that were configured in Python previously. \n",
        "\n",
        "Let's start an API instance "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "B1DQyB5ErIzr",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7e170445-bc93-4660-b944-8b10b8b02d98"
      },
      "source": [
        "!killall -9 uvicorn\n",
        "!CONFIG=workflow.yml nohup uvicorn \"txtai.api:app\" &> api.log &\n",
        "!sleep 30\n",
        "!cat api.log"
      ],
      "execution_count": 78,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "INFO:     Started server process [754]\n",
            "2022-06-17 15:05:58,554 [INFO] serve: Started server process [754]\n",
            "INFO:     Waiting for application startup.\n",
            "2022-06-17 15:05:58,554 [INFO] startup: Waiting for application startup.\n",
            "INFO:     Application startup complete.\n",
            "2022-06-17 15:06:07,707 [INFO] startup: Application startup complete.\n",
            "INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n",
            "2022-06-17 15:06:07,707 [INFO] _log_started_message: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "45JaR7Nr0Zmg"
      },
      "source": [
        "Next we'll execute the workflow. txtai has API bindings for [JavaScript](https://github.com/neuml/txtai.js), [Java](https://github.com/neuml/txtai.java), [Rust](https://github.com/neuml/txtai.rs) and [Golang](https://github.com/neuml/txtai.go). But to keep things simple, we'll just run the commands via cURL. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "xt_qL6eA0SrS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3ca70a31-cf48-42b4-949f-f01aac14505c"
      },
      "source": [
        "# Execute workflow via API call\n",
        "!curl -X POST \"http://localhost:8000/workflow\" -H  \"accept: application/json\" -H  \"Content-Type: application/json\" -d \"{\\\"name\\\":\\\"index\\\",\\\"elements\\\":[\\\"all:aliens\\\"]}\""
      ],
      "execution_count": 79,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[[\"http://arxiv.org/abs/2102.01522v3\",\"If Loud Aliens Explain Human Earliness, Quiet Aliens Are Also Rare\",null],[\"http://arxiv.org/abs/cs/0306071v1\",\"AliEnFS - a Linux File System for the AliEn Grid Services\",null],[\"http://arxiv.org/abs/physics/0306103v1\",\"AliEn - EDG Interoperability in ALICE\",null],[\"http://arxiv.org/abs/2103.05559v1\",\"Oumuamua Is Not a Probe Sent to our Solar System by an Alien\\n  Civilization\",null],[\"http://arxiv.org/abs/1403.3979v1\",\"Robust transitivity and density of periodic points of partially\\n  hyperbolic diffeomorphisms\",null],[\"http://arxiv.org/abs/1712.09210v1\",\"Sampling alien species inside and outside protected areas: does it\\n  matter?\",null],[\"http://arxiv.org/abs/cs/0306067v1\",\"The AliEn system, status and perspectives\",null],[\"http://arxiv.org/abs/0707.0011v2\",\"Calculating the probability of detecting radio signals from alien\\n  civilizations\",null],[\"http://arxiv.org/abs/1805.04278v1\",\"Field Trial of Alien Wavelengths on GARR Optical Network\",null],[\"http://arxiv.org/abs/1808.00529v1\",\"Open Category Detection with PAC Guarantees\",null],[\"http://arxiv.org/abs/1206.3640v1\",\"The Study of Climate on Alien Worlds\",null],[\"http://arxiv.org/abs/1203.6805v2\",\"Aliens on Earth. Are reports of close encounters correct?\",null],[\"http://arxiv.org/abs/1604.05078v1\",\"The Imprecise Search for Habitability\",null],[\"http://arxiv.org/abs/1006.2613v1\",\"Resurgence, Stokes phenomenon and alien derivatives for level-one linear\\n  differential systems\",null],[\"http://arxiv.org/abs/1307.0653v1\",\"General and alien solutions of a functional equation and of a functional\\n  inequality\",null],[\"http://arxiv.org/abs/1705.03394v1\",\"That is not dead which can eternal lie: the aestivation hypothesis for\\n  resolving Fermi's paradox\",null],[\"http://arxiv.org/abs/1701.02294v1\",\"Alien Calculus and non perturbative effects in Quantum Field Theory\",null],[\"http://arxiv.org/abs/1801.06180v1\",\"Are Alien Civilizations Technologically Advanced?\",null],[\"http://arxiv.org/abs/1902.05387v1\",\"Simultaneous x, y Pixel Estimation and Feature Extraction for Multiple\\n  Small Objects in a Scene: A Description of the ALIEN Network\",null],[\"http://arxiv.org/abs/0711.4034v1\",\"The q-analogue of the wild fundamental group (II)\",null],[\"http://arxiv.org/abs/2111.07895v1\",\"Research Programs Arising from 'Oumuamua Considered as an Alien Craft\",null],[\"http://arxiv.org/abs/2112.15226v1\",\"Variations on the Resurgence of the Gamma Function\",null],[\"http://arxiv.org/abs/astro-ph/0501119v1\",\"Expanding advanced civilizations in the universe\",null],[\"http://arxiv.org/abs/cs/0306068v1\",\"AliEn Resource Brokers\",null],[\"http://arxiv.org/abs/hep-ph/9403231v2\",\"The Renormalization of Composite Operators in Yang-Mills Theories Using\\n  General Covariant Gauge\",null]]"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_bwn4KBt1Cos"
      },
      "source": [
        "The data is now indexed. Note that the index configuration has an `upsert` action. Each workflow call will insert new rows or update existing rows. This call could be scheduled with a system cron to execute periodically and build an index of arXiv article titles. \n",
        "\n",
        "Now that the index is ready, let's run a search."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qbteIueJ1Fds",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ad8ab84b-36a3-4346-d387-64321b933d25"
      },
      "source": [
        "# Run a search\n",
        "!curl -X GET \"http://localhost:8000/search?query=radio&limit=3\" -H  \"accept: application/json\""
      ],
      "execution_count": 80,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[{\"id\":\"http://arxiv.org/abs/0707.0011v2\",\"score\":0.40350058674812317},{\"id\":\"http://arxiv.org/abs/1805.04278v1\",\"score\":0.3406212031841278},{\"id\":\"http://arxiv.org/abs/1902.05387v1\",\"score\":0.22262491285800934}]"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "C5_Tt6EA3Cxb"
      },
      "source": [
        "# Add a translation step to workflow\n",
        "\n",
        "Next we'll recreate the workflow, adding one additional step, translating the text into French before indexing. This workflow runs an arXiv query, translates the results and builds an semantic index of titles in French. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "j8rBVl17293q",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "215dc2cf-3a57-4deb-820d-e8ac03e3e041"
      },
      "source": [
        "%%writefile workflow.yml\n",
        "# Index settings\n",
        "writable: true\n",
        "embeddings:\n",
        "    path: sentence-transformers/nli-mpnet-base-v2\n",
        "\n",
        "# Tabular pipeline\n",
        "tabular:\n",
        "  idcolumn: id\n",
        "  textcolumns: \n",
        "    - title\n",
        "\n",
        "# Translation pipeline\n",
        "translation:\n",
        "\n",
        "# Workflow definitions\n",
        "workflow:\n",
        "  index:\n",
        "    tasks:\n",
        "      - task: service\n",
        "        action: tabular\n",
        "        url: http://export.arxiv.org/api/query?max_results=25\n",
        "        method: get\n",
        "        params:\n",
        "          search_query: null\n",
        "        batch: false\n",
        "        extract: [feed, entry]\n",
        "      - action: translation\n",
        "        args: [fr]\n",
        "      - action: upsert"
      ],
      "execution_count": 81,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Overwriting workflow.yml\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UQWvvgb2CwgG",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3b0c99d7-b5f6-4c81-eb6e-ac9055eaaae4"
      },
      "source": [
        "!killall -9 uvicorn\n",
        "!CONFIG=workflow.yml nohup uvicorn \"txtai.api:app\" &> api.log &\n",
        "!sleep 30\n",
        "!cat api.log"
      ],
      "execution_count": 82,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "INFO:     Started server process [775]\n",
            "2022-06-17 15:06:29,397 [INFO] serve: Started server process [775]\n",
            "INFO:     Waiting for application startup.\n",
            "2022-06-17 15:06:29,397 [INFO] startup: Waiting for application startup.\n",
            "INFO:     Application startup complete.\n",
            "2022-06-17 15:06:40,198 [INFO] startup: Application startup complete.\n",
            "INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n",
            "2022-06-17 15:06:40,199 [INFO] _log_started_message: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "v1y4heYx679i"
      },
      "source": [
        "Same as before, we'll run the index workflow and a search"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "npW3rjCw6_nx",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "fba0bd30-2340-4197-d68c-4fc925ce80b8"
      },
      "source": [
        "# Execute workflow via API call\n",
        "!curl -s -X POST \"http://localhost:8000/workflow\" -H  \"accept: application/json\" -H  \"Content-Type: application/json\" -d \"{\\\"name\\\":\\\"index\\\",\\\"elements\\\":[\\\"all:aliens\\\"]}\" > /dev/null\n",
        "\n",
        "# Run a search\n",
        "!curl -X GET \"http://localhost:8000/search?query=radio&limit=3\" -H  \"accept: application/json\""
      ],
      "execution_count": 83,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[{\"id\":\"http://arxiv.org/abs/0707.0011v2\",\"score\":0.532800555229187},{\"id\":\"http://arxiv.org/abs/0711.4034v1\",\"score\":0.24413327872753143},{\"id\":\"http://arxiv.org/abs/2102.01522v3\",\"score\":0.22881504893302917}]"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OsQO5DG9zBQF"
      },
      "source": [
        "# Run YAML workflow in Python\n",
        "\n",
        "Workflow YAML files can also be directly executed in Python. In this case, all input data is passed locally in Python and not through network interfaces. The following section shows how to do this!"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iXmkLDTlzPT3",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6b795963-2954-42e2-c42d-39c3f88c9ac3"
      },
      "source": [
        "import yaml\n",
        "\n",
        "from txtai.app import Application\n",
        "\n",
        "with open(\"workflow.yml\") as config:\n",
        "  workflow = yaml.safe_load(config)\n",
        "\n",
        "app = Application(workflow)\n",
        "\n",
        "# Run the workflow\n",
        "data = list(app.workflow(\"index\", [\"all:aliens\"]))\n",
        "\n",
        "# Run a search\n",
        "for result in app.search(\"radio\", None):\n",
        "  text = [row[1] for row in data if row[0] == result[\"id\"]][0]\n",
        "  print(result[\"id\"], result[\"score\"], text)"
      ],
      "execution_count": 84,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "http://arxiv.org/abs/0707.0011v2 0.532800555229187 Calcul de la probabilité de détection des signaux radio de l'étrangercivilisations\n",
            "http://arxiv.org/abs/0711.4034v1 0.24413327872753143 Le q-analogue du groupe fondamental sauvage (II)\n",
            "http://arxiv.org/abs/2102.01522v3 0.22881504893302917 Si les étrangers louds expliquent le début de l'humanité, les étrangers tranquilles sont aussi rares\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EoQFEi_61P9O"
      },
      "source": [
        "# Wrapping up\n",
        "\n",
        "This notework demonstrated how to transform, index and search tabular data from a variety of sources. txtai offers maximum flexibility in building composable workflows to maximize the number of ways data can be indexed for semantic search. "
      ]
    }
  ]
}
